import { Song, Comment } from '@/model';
import { ElNotification } from 'element-plus';
import { storageType, elMessageType } from '@/model/enum';
import useThemeStore from '@/store/theme';
import { storeToRefs } from 'pinia';
import { Ref, nextTick } from 'vue';
import { getMusicUrl, searchMusic } from '@/api'
import router from '@/router/index';

// 获取当前时间的时间戳
export const getTimeStamp = (): number => {
    return new Date().getTime();
};

// 将时间转换为时间戳
export const formatToTimeStap = (time: string): number => {
    if (time.includes('.')) {
        const min = time.split(':')[0];
        const ms = time.split(':')[1];
        return +min * 60 * 1000 + +ms * 1000;
    } else {
        const min = time.split(':')[0];
        const s = time.split(':')[1].split('.')[0];
        return +min * 60 * 1000 + +s * 1000;
    }
};

// 创建一个elmessage的提示
export const elMessage = (type: string = 'success', msg: string): void => {
    switch (type) {
        case elMessageType.SUCCESS:
            ElNotification.success({
                title: 'Success',
                message: msg,
                duration: 1000
            });
            break;
        case elMessageType.ERROR:
            ElNotification.error({
                title: 'Error',
                message: msg,
                duration: 1000
            });
            break;
        case elMessageType.INFO:
            ElNotification.info({
                title: 'Infomation',
                message: msg,
                duration: 1000
            });
            break;
        case elMessageType.WARNING:
            ElNotification.info({
                title: 'Warning',
                message: msg,
                duration: 1000
            });
            break;
    }
};

// 设置浏览器本地存储
export const setStorAge = (type: string, key: string, value: any): void => {
    switch (type) {
        case storageType.LOCAL:
            {
                if (typeof value == 'object') {
                    localStorage.setItem(key, JSON.stringify(value));
                } else {
                    localStorage.setItem(key, value);
                }
            }

            break;
        case storageType.SESSION:
            {
                if (typeof value == 'object') {
                    sessionStorage.setItem(key, JSON.stringify(value));
                } else {
                    sessionStorage.setItem(key, value);
                }
            }
            break;
    }
};

// 获取浏览器本地存储
export const getStorage = (type: string, key: string): any => {
    switch (type) {
        case storageType.LOCAL: {
            try {
                return JSON.parse(localStorage.getItem(key) as string);
            } catch {
                return localStorage.getItem(key);
            }
        }
        case storageType.SESSION: {
            try {
                return JSON.parse(sessionStorage.getItem(key) as string);
            } catch {
                return sessionStorage.getItem(key);
            }
        }
    }
};

// 获取主题
export const getTheme = (): Map<string, Ref<string>> => {
    const themes = useThemeStore()
    const {
        fontBlack,
        fontColor,
        searchBg,
        background,
        menuColor,
        tableHover,
        shadow,
        active,
        themeColor,
        fontGray
    } = storeToRefs(themes);
    const themeMap: Map<string, Ref<string>> = new Map()
    themeMap.set('fontBlack', fontBlack);
    themeMap.set('fontColor', fontColor);
    themeMap.set('searchBg', searchBg);
    themeMap.set('background', background);
    themeMap.set('menuColor', menuColor);
    themeMap.set('tableHover', tableHover);
    themeMap.set('shadow', shadow);
    themeMap.set('active', active);
    themeMap.set('themeColor', themeColor);
    themeMap.set('fontGray', fontGray);
    return themeMap;

}

// 请求数据时附带加载动画
export const getRequest = (getData: () => void, loading?: Ref<boolean>) => {
    if (loading) {
        loading.value = true
    }
    getData()
}

// 从返回数据中获取音乐信息，并放入容器
export const getMusicInfos = (ids: string[], list: Song[], data: any) => {
    // ar歌手列表 al专辑 fee是否有版权或者会员 dt歌曲时长
    const { id, name, ar, al, fee, dt } = data
    ids.push(id)
    list.push({
        id: id,
        name: name,
        singer: ar.map((item: any) => item.name).join('、'),
        songImage: al.picUrl,
        album: al.name,
        available: fee,
        time: dt,
        url: ''
    })
}


// 获取音乐的url
// ids是通过，分割的多个id,list是放歌曲的容器,key字段判断要不要做持久化
export const getMusicUrls = async (
    ids: string,
    list: Song[],
    key?: string,
    exclude?: number
) => {
    try {
        // id映射
        const mapper: Map<string, number> = new Map(
            list.map((item, index) => [item.id, index])
        );
        // 当数据量过大时分批请求
        const idArr = list.map((item) => item.id);
        const requestArr: any[] = [];
        for (let i = 0; i < Math.ceil(idArr.length / 100); i++) {
            requestArr.push(
                getMusicUrl(idArr.slice(i * 100, (i + 1) * 100).join(','))
            );
        }
        const responseArr = await Promise.all(requestArr);
        responseArr.forEach((response: any) => {
            const { data } = response;
            data.forEach((item: any) => {
                const index = mapper.get(item.id) as number;
                if (item.url) {
                    if (exclude != undefined) {
                        if (index != exclude) {
                            list[index].url = item.url;
                        }
                    } else {
                        list[index].url = item.url;
                    }
                } else {
                    list[index].available = '10';
                    list[index].url = '';
                }
            });
        });
        // 判断key要不要做持久化
        if (key) {
            setStorAge(storageType.SESSION, key, list);
        }
    } catch (err: any) {
        console.log('出错了');
        // elMessage(elMessageType.ERROR, err.message);
    }
};

// 从评论的返回值中提取数据
export const getComment = (comments: any, target: Comment[]) => {
    const idMap: Map<string, string> = new Map();
    if (target.length > 0) {
        target.forEach((item) => {
            idMap.set(item.commentId, item.commentId);
        });
    }
    comments.forEach((item: any) => {
        const {
            user: { avatarUrl, nickname },
            content,
            commentId,
            time,
            likedCount,
            ipLocation: { location }
        } = item;
        let { beReplied } = item;
        if (beReplied) {
            beReplied = beReplied.map((item: any) => {
                const {
                    user: { avatarUrl, nickname },
                    content,
                    beRepliedCommentId,
                    ipLocation: { location }
                } = item;
                const comment: Comment = {
                    commentId: beRepliedCommentId,
                    nickname,
                    content,
                    time: '',
                    likeCount: '0',
                    avatar: avatarUrl,
                    ip: location
                };
                return comment;
            });
        }
        if (!idMap.get(commentId)) {
            target.push({
                nickname,
                avatar: avatarUrl,
                content,
                time,
                likeCount: likedCount,
                commentId,
                reply: beReplied,
                ip: location
            });
        }
    });
};



// 转换时间，将毫秒的时间转为00:00类型的时间
export const transformTime = (time: string): string => {
    const temp: number = Math.floor(+time / 1000);
    const seconds: string = temp % 60 < 10 ? '0' + (temp % 60) : '' + (temp % 60);
    const minutes: string =
        temp / 60 < 10 ? '0' + Math.floor(temp / 60) : '' + Math.floor(temp / 60);
    return minutes + ':' + seconds;
};

// 将字符串毫秒时间进行转化为妙
export const transformTotalTime = (time: string): number => {
    return +time / 1000;
};

// 将时间戳格式化为year-month-day格式
export const formatTime = (time: string): string => {
    const date: Date = new Date(time);
    return (
        date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    );
};

// 处理歌手名字
export const handleSingerName = (name: string) => {
    return name.includes('、') ? name.split('、')[0] : name
}

// 分享
export const share = (content: string, tip?: string) => {
    navigator.clipboard.writeText(content);
    elMessage(
        elMessageType.SUCCESS,
        tip ? tip : '已成功复制到剪切板，快去分享吧！'
    );
};

// 前往音乐的MV
export const playVideo = (song: Song, beforeGo: () => void) => {
    getRequest(async () => {
        console.log(song);
        // 获取mv
        try {
            const response: any = await searchMusic(
                1014,
                1,
                song.name + '' + handleSingerName(song.singer)
            )
            const { result: { videos } } = response
            console.log(videos);
            if (videos && videos.length > 0) {
                beforeGo()
                await nextTick()
                router.push({
                    name: 'video',
                    query: {
                        id: videos[0].vid
                    }
                })
            } else {
                elMessage(elMessageType.INFO, '该歌曲暂无mv.');
            }
        } catch (err: any) {
            elMessage(elMessageType.ERROR, err.message);
        }
    })
}